import 'dart:async';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'login.dart';
import 'scan_sign.dart';
import 'scan_add_class.dart';

void main() => runApp(stu_comsic());

class stu_comsic extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Row(
            children: [
              Container(
                width: 45,
                height: 45,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.blue, // 修改圆形的颜色
                ),
                child: Center(
                  child: Text(
                    '文睿',
                    style: TextStyle(
                      fontSize: 15.0,
                      color: Colors.white, // 修改圆形里面的字体颜色
                    ),
                  ),
                ),
              ),
              SizedBox(width: 20),
              Text(
                '你好，文睿',
                style: TextStyle(
                  fontSize: 13.0,
                  color: Colors.black, // 修改右侧字体颜色
                ),
              ),
              SizedBox(width: 150),
            ],
          ),
        ),
        body: stu_HomePage(),
      ),
    );
  }
}

class stu_HomePage extends StatefulWidget {
  @override
  _stu_HomePageState createState() => _stu_HomePageState();
}

class _stu_HomePageState extends State<stu_HomePage> {
  int _currentIndex = 1;
  final List<Widget> _pages = [
    stu_MessagesPage(),
    stu_ComsicPage(),
    stu_MinePage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pages[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.message),
            label: '课表',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '签到',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '我的',
          ),
        ],
      ),
    );
  }
}

class stu_ComsicPage extends StatefulWidget {
  @override
  _stu_ComsicPageState createState() => _stu_ComsicPageState();
}

class _stu_ComsicPageState extends State<stu_ComsicPage> {
  String currentTime = "";
  List<bool> isChecklists = [false, false, false, false];

  @override
  void initState() {
    super.initState();
    Timer.periodic(Duration(seconds: 1), (Timer timer) {
      DateTime now = DateTime.now();
      // 移除小数点后的数字
      currentTime =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} '
          '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}';
      setState(() {
        // currentTime = DateTime.now().toString();
      });
    });
  }

  Future<void> signIn() async {
    String jwtToken = await retrieveJwtToken('access_token');
    if (jwtToken == '' && !isJwtExpired(jwtToken)) {
      print('No JWT token found or expire.');
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Login()),
      );
      return;
    }
    String apiUrl =
        "http://10.161.4.248:8080/v1/attendance"; // Replace with your API URL

    try {
      var response = await http.post(Uri.parse(apiUrl),
          headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer $jwtToken"
          },
          body: jsonEncode({"sign_code": "70656"}));

      if (response.statusCode == 200) {
        // Handle the response
        print("Sign-in successful");
      } else {
        // Handle error
        print("Failed to sign in: ${response.body}");
      }
    } catch (e) {
      // Handle exception
      print("Error occurred: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final Width = size.width;
    final Height = size.height;
    return Container(
      width: Width,
      height: Height,
      color: Colors.grey[100], // 设置底色为浅灰色
      child: Column(children: [
        SizedBox(height: 0.05 * Height),
        Container(
            width: 0.88 * Width,
            height: 0.07 * Height,
            child: Row(children: [
              SizedBox(width: 0.02 * Width),
              Container(
                  width: 0.6 * Width,
                  height: 0.07 * Height,
                  decoration: BoxDecoration(
                    color: Colors.white, // 设置矩形底色为白色
                    borderRadius: BorderRadius.circular(8), // 设置圆角
                    boxShadow: [
                      BoxShadow(color: Colors.grey.shade200, blurRadius: 8)
                    ],
                  ),
                  child: Center(child: stu_SelectClass())),
              SizedBox(width: 0.03 * Width),
              MaterialButton(
                  //背景颜色
                  color: Colors.white,
                  //边框样式
                  shape: const RoundedRectangleBorder(
                    //边框圆角
                    borderRadius: BorderRadius.all(
                      Radius.circular(8),
                    ),
                  ),
                  //按钮高度
                  minWidth: 0.05 * Width,
                  height: 0.07 * Height,
                  //点击事件
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => JoinClassPage()),
                    );
                  },
                  child: const Text(
                    "加入班级",
                    style: TextStyle(fontSize: 14, color: Colors.black87),
                  ))
            ])),
        SizedBox(height: 0.05 * Height),
        Container(
          width: 0.82 * Width,
          height: 0.18 * Height,
          decoration: BoxDecoration(
            color: Colors.white, // 设置矩形底色为白色
            borderRadius: BorderRadius.circular(8), // 设置圆角
            boxShadow: [BoxShadow(color: Colors.grey.shade200, blurRadius: 8)],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '签到方式:',
                style: TextStyle(fontSize: 16),
              ),
              SizedBox(width: 0.05 * Width),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      Checkbox(
                        value: isChecklists[0],
                        onChanged: (bool? value) {
                          // TODO
                          setState(() {
                            isChecklists[0] = value!;
                          });
                        },
                      ),
                      Text('WIFI'),
                    ],
                  ),
                  Row(
                    children: [
                      Checkbox(
                        value: isChecklists[1],
                        onChanged: (bool? value) {
                          // TODO
                          setState(() {
                            isChecklists[1] = value!;
                          });
                        },
                      ),
                      Text('NFC'),
                    ],
                  ),
                ],
              ),
              SizedBox(width: 0.05 * Width),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      Checkbox(
                        value: isChecklists[2],
                        onChanged: (bool? value) {
                          // TODO
                          setState(() {
                            isChecklists[2] = value!;
                          });
                        },
                      ),
                      Text('扫码'),
                    ],
                  ),
                  Row(
                    children: [
                      Checkbox(
                        value: isChecklists[3],
                        onChanged: (bool? value) {
                          // TODO
                          setState(() {
                            isChecklists[3] = value!;
                          });
                        },
                      ),
                      Text('蓝牙'),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
        SizedBox(height: 0.05 * Height),
        Container(
          width: 0.82 * Width,
          height: 0.26 * Height,
          decoration: BoxDecoration(
            color: Colors.white, // 设置矩形底色为白色
            borderRadius: BorderRadius.circular(8), // 设置圆角
            boxShadow: [BoxShadow(color: Colors.grey.shade200, blurRadius: 8)],
          ),
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            Text(
              currentTime,
              style: TextStyle(fontSize: 26),
            ),
            SizedBox(height: 0.04 * Height),
            MaterialButton(
                //背景颜色
                color: Colors.blue,
                //边框样式
                shape: const RoundedRectangleBorder(
                  //边框圆角
                  borderRadius: BorderRadius.all(
                    Radius.circular(40),
                  ),
                ),
                //按钮高度
                minWidth: 0.4 * Width,
                height: 0.08 * Height,
                //点击事件
                onPressed: () {
                  // signIn();
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => ScanAttendancePage()),
                  );
                },
                child: const Text(
                  "签到",
                  style: TextStyle(fontSize: 22, color: Colors.white),
                )),
          ]),
        ),
      ]),
    );
  }
}

class stu_SelectClass extends StatefulWidget {
  @override
  _stu_SelectClass createState() => _stu_SelectClass();
}

class _stu_SelectClass extends State<stu_SelectClass> {
  List<String> courseOptions = [
    '软件工程 8:30-11:50',
    '机器学习导论 8:30-11:50',
    '数据库系统 14:00-15:30',
    '计算机网络 8:30-10:00'
  ];
  String selectedValue = '软件工程 8:30-11:50';

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final Width = size.width;
    final Height = size.height;

    return Container(
      width: 0.6 * Width,
      height: 0.07 * Height,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(color: Colors.grey.shade200, blurRadius: 8),
        ],
      ),
      child: Center(
        child: DropdownButton<String>(
          value: selectedValue,
          onChanged: (String? newValue) {
            setState(() {
              selectedValue = newValue!;
            });
          },
          items: courseOptions.map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
        ),
      ),
    );
  }
}

class stu_MessagesPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        'Messages Page',
        style: TextStyle(fontSize: 24),
      ),
    );
  }
}

class stu_MinePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        'Profile Page',
        style: TextStyle(fontSize: 24),
      ),
    );
  }
}
